package com.ydj.app.service;

import com.ydj.app.entity.CmsAccount;
import com.ydj.app.entity.Kol;
import com.ydj.app.entity.dao.KolDao;
import com.ydj.app.entity.query.KolQuery;
import com.ydj.app.excel.KolListExcelDataToWrite;
import com.ydj.app.protocol.http.cms.*;
import com.ydj.framework.exception.CommonException;
import com.ydj.framework.filter.ExtHttpServletResponse;
import com.ydj.framework.mysql.PageArgs;
import com.ydj.framework.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * KOL相关服务
 */
@Slf4j
@Service
public class KolService {
    @Value("${app.shareUrl}")
    private String shareUrl;

    @Value("${app.rebateCommission}")
    private Integer rebateCommission;

    @Autowired
    private KolDao kolDao;

    /**
     * 列表
     */
    public CmsKolListRes cmsList(CmsKolListReq req, CmsAccount account) {
        PageArgs pageArgs = req.getPageArgs();

        List<Kol> list = new KolQuery(kolDao)
                .nameLike(req.getName())
                .accountLike(req.getAccount())
                .page(pageArgs);

        CmsKolListRes res = new CmsKolListRes(pageArgs);
        for (Kol kol : list) {
            CmsKolListRes.CmsKolListResItem item = new CmsKolListRes.CmsKolListResItem()
                    .setId(kol.getId())
                    .setName(kol.getName())
                    .setJoinTime(kol.getCreateTime())
                    .setAccount(kol.getAccount())
                    .setInviteUrl(shareUrl + kol.getAccount())
                    .setTotalInviteCount(kol.getTotalInviteCount())
                    .setTotalSettledCount(kol.getTotalSettledCount())
                    .setTotalUnsettledCount(kol.getTotalUnsettledCount())
                    .setTotalUnsettledPrice(kol.getTotalUnsettledCount() * rebateCommission);
            res.getList().add(item);
        }
        return res;
    }

    /**
     * 新增
     */
    public CmsKolCreateRes cmsCreate(CmsKolCreateReq req, CmsAccount account) throws CommonException {
        Kol existKol = new KolQuery(kolDao)
                .account(req.getAccount())
                .single();
        if (existKol != null) {
            CommonException.throwException("账号重复了");
        }
        Kol kol = new Kol()
                .setName(req.getName())
                .setAccount(req.getAccount())
                .setTotalInviteCount(0)
                .setTotalSettledCount(0)
                .setTotalUnsettledCount(0);
        kolDao.saveOrUpdate(kol);

        return new CmsKolCreateRes()
                .setId(kol.getId());
    }

    /**
     * 修改
     */
    public void cmsUpdate(CmsKolUpdateReq req, CmsAccount account) throws CommonException {
        Kol existKol = new KolQuery(kolDao)
                .account(req.getAccount())
                .single();
        if (existKol != null && !existKol.getId().equals(req.getId())) {
            CommonException.throwException("账号重复了");
        }

        Kol kol = new KolQuery(kolDao)
                .id(req.getId())
                .single();
        CommonException.throwExceptionIfNull(kol, "KOL不存在");

        kol.setName(req.getName())
                .setAccount(req.getAccount());

        kolDao.saveOrUpdate(kol);
    }

    /**
     * 删除
     */
    public void cmsDelete(CmsKolDeleteReq req, CmsAccount account) throws CommonException {
        Kol kol = new KolQuery(kolDao)
                .id(req.getId())
                .single();
        CommonException.throwExceptionIfNull(kol, "KOL不存在");

        kolDao.removeById(req.getId());
    }

    /**
     * 结算
     */
    public void cmsSettle(CmsKolSettleReq req, CmsAccount account) throws CommonException {
        Kol kol = new KolQuery(kolDao)
                .id(req.getId())
                .single();
        CommonException.throwExceptionIfNull(kol, "KOL不存在");

        kol.setTotalSettledCount(kol.getTotalInviteCount())
                .setTotalUnsettledCount(0);
        kolDao.saveOrUpdate(kol);
    }

    /**
     * 导出Excel
     */
    public void cmsExportExcel(ExtHttpServletResponse response, CmsKolExportExcelReq req, CmsAccount account) throws CommonException, IOException {
        List<Kol> list = new KolQuery(kolDao)
                .nameLike(req.getName())
                .accountLike(req.getAccount())
                .list();

        // 导出的数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<KolListExcelDataToWrite> rowData = new LinkedList<>();
        int seq = 0;
        for (Kol kol : list) {
            KolListExcelDataToWrite row = new KolListExcelDataToWrite();
            seq++;
            row.setSeq(String.valueOf(seq));
            if (kol.getName() != null) {
                row.setName(kol.getName());
            }
            if (kol.getCreateTime() != null) {
                row.setCreateTime(sdf.format(kol.getCreateTime()));
            }
            if (kol.getTotalInviteCount() != null) {
                row.setInviteCount(kol.getTotalInviteCount());
            }
            if (kol.getTotalSettledCount() != null) {
                row.setSettledCount(kol.getTotalSettledCount());
            }
            if (kol.getTotalUnsettledCount() != null) {
                row.setUnsettledCount(kol.getTotalUnsettledCount());
            }
            if (kol.getAccount() != null) {
                row.setInviteUrl(shareUrl + kol.getAccount());
            }
            rowData.add(row);
        }

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("now", DateUtils.dateToString(new Date()));
        mapData.put("totalKolCount", rowData.size());
        mapData.put("totalInviteCount", rowData.stream().mapToInt(row->row.getInviteCount()).sum());
        mapData.put("totalSettledCount", rowData.stream().mapToInt(row->row.getSettledCount()).sum());
        mapData.put("totalUnsettledCount", rowData.stream().mapToInt(row->row.getUnsettledCount()).sum());

        String excelFileName = "KOL信息表";
        String templateResPath = "template.excel/KolListTemplate.xlsx";

        response.outputExcel(rowData, mapData, excelFileName, templateResPath);
    }
}